import TabBar from './components/TabBar';
import './App.scss';
import AppRouter from './routes';
import React, { Component,Suspense } from 'react'
import {changeMusicNode,changeMusicSrcAsync,changeMusicCurrentDetail,changeMusicCurrentTime} from './store/actions/music'
import {changeLogin} from './store/actions/login'
import {formatSeconds} from './utils/index'
import './assets/css/iconfont.css'
import {connect} from 'react-redux';
 class App extends Component {
  state = { 
    pathName:window.location.pathname,
    timer:null,
  }
  initTabbarHeight =()=>{
    let tabbarHeight = 0
    this.props.isShowTarbar===true?tabbarHeight=50:tabbarHeight=0
    this.contentHeight.style.height = (window.innerHeight - tabbarHeight ) + 'px'
    this.contentHeight.style.overflow = 'scroll'
  }
  componentDidMount(){
    this.initTabbarHeight()
    this.props.changeMusicNode(this.audio)
  }

  componentDidUpdate(prevProps, prevState, snapshot){
    let that = this
    this.initTabbarHeight()
    this.contentHeight.style.overflow = 'scroll'
    this.audio.onplay = function(){
      that.timer = setInterval(() => {
        let seconds = that.audio.currentTime
        that.props.changeMusicCurrentTime({
            ms:formatSeconds(seconds,'m:s'),
            s:seconds
        })
      }, 500);
    }
    this.audio.onpause = function(){
      clearInterval(that.timer)
    }
    this.audio.onended = function() {
      that.props.playOrder===0?console.log('循环播放'):that.nextSong()
    };
  }
  componentWillUnmount(){
    clearInterval(this.timer)
  }

  nextSong=()=>{
    const {musicList,musicSrc,changeMusicSrcAsync,changeMusicCurrentDetail} =this.props
    musicList.map((item,index)=>{
      if(musicSrc.id===item.id){
        let song = (index===musicList.length-1) ? musicList[0] : musicList[index+1]
        changeMusicSrcAsync(song.id)
        changeMusicCurrentDetail(song)
      }
    })
  }
  render() {
    const {playOrder,musicSrc}= this.props
    return (
      <div>
        <div ref={Ndom => this.contentHeight = Ndom}>
          <Suspense fallback={<div>Loading...</div>}>
            <AppRouter/>
          </Suspense>
        </div>
        <audio ref={(n)=>this.audio=n} src={musicSrc?musicSrc.src:''} loop={playOrder===0?true:false} />
        <div ref={Ndom => this.tabBarHeight =Ndom}>
          <TabBar/>
        </div>
    </div>
    )
  }
}


export default  connect(
  state =>({
    isShowTarbar:state.isShowTarbar,
    musicSrc:state.musicSrc,
    musicList:state.musicList,
    playOrder:state.playOrder,
    musicCurrentTime:state.musicCurrentTime
  }),{
    changeMusicNode,
    changeMusicSrcAsync,
    changeMusicCurrentDetail,
    changeMusicCurrentTime,
    changeLogin
  }
)(App)
